package com.bw.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.app.func.TableProcessHoKFunction;
import com.bw.bean.TableProcess;
import com.bw.utils.MyHBaseSinkFunction;
import com.bw.utils.MyKafkaUtil;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.OutputTag;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;

/**
 * @ProjectName: BigData
 * @Package: com.bw.app.dwd
 * @ClassName: BaseDBApp
 * @Author: Gy
 * @Description: 准备业务数据的DWD层
 * @Date: 2021/11/10 16:52
 */
public class BaseDBAppNew {
    public static void main(String[] args) throws Exception {
        //todo 1.准备环境
        //1.1 创建流处理执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(1);

        //todo 2.从Kafka的ODS层读取数据
        String topic = "ods_base_db_m";
        String groupId = "base_db_app_group";
        //2.1 通过工具类获取Kafka的消费者
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        DataStreamSource<String> jsonStrDs = env.addSource(kafkaSource);
        //todo 3.对DS中数据进行结构的转换      String-——》Json
        SingleOutputStreamOperator<JSONObject> jsonObjDs = jsonStrDs.map(jsonStr -> JSON.parseObject(jsonStr));

        //todo 4.对数据进行ETL 如果table为空 或者 data为空，或者长度<3 将这样的数据过滤掉
        SingleOutputStreamOperator<JSONObject> filteredDs = jsonObjDs.filter(
                jsonObj -> {
                    boolean b = jsonObj.getString("table") != null
                            && jsonObj.getJSONObject("data") != null
                            && jsonObj.getString("data").length() > 3;
                    return b;
                }
        );

        //todo 5. 动态分流 事实表放到主流，写回到Kafka的DWD层；如果维度表，通过侧输出流，写入到HBASE
        //5.1 定义输出到HBASE的测输出流标签
        OutputTag<JSONObject> hbaseTag = new OutputTag<JSONObject>(TableProcess.SINK_TYPE_HBASE) {};

        //主流输出到kafka
        SingleOutputStreamOperator<JSONObject> process = filteredDs.process(new TableProcessHoKFunction(hbaseTag));
        //侧输出流将来输出到hbase中去
        DataStream<JSONObject> sideOutput = process.getSideOutput(hbaseTag);

        //侧输出流的数据直接写入hbase中的表
        sideOutput.addSink(new MyHBaseSinkFunction());
        //根据传输的数据比较将数据分流，如果成功为true
        FlinkKafkaProducer<JSONObject> kafkaSinkBySchema = MyKafkaUtil.getKafkaSinkBySchema(new KafkaSerializationSchema<JSONObject>() {
            @Override
            public void open(SerializationSchema.InitializationContext context) throws Exception {
                System.out.println("虚拟化kafka-topic 数据");
            }

            @Override
            public ProducerRecord<byte[], byte[]> serialize(JSONObject jsonObject, @Nullable Long aLong) {
                String sinkTopic = jsonObject.getString("sink_table");
                JSONObject data = jsonObject.getJSONObject("data");
                return new ProducerRecord<>(sinkTopic, data.toString().getBytes());
            }
        });
        //将kafka 数据进行分流到dwd去
        process.addSink(kafkaSinkBySchema);
        env.execute();
    }
}